import os
import sys

def RegistMainFunction(entry):
	str_ext = "extern int " + entry + "(int, char**);\n"
	func = entry[0:entry.rfind("_")]
	str_reg = "\tConsoleRegister(\"" + func + "\", (void*)" + entry + ");\n"
	return str_ext, str_reg

def ReadFile(filename):
	file = open(filename, "r", encoding="utf-8")
	line = " "
	need_next_line = False
	str_ext = ""
	str_reg = ""
	while line:
		line = file.readline()
		if len(line) > 0:
			if "@RegistMainFunction" in line:
				need_next_line = True
			elif need_next_line :
				need_next_line = False
				i_start = line.find(" ")
				i_end = line.find("(")
				func = line[i_start:i_end].replace("*", "").strip()
				text = RegistMainFunction(func)
				str_ext += text[0]
				str_reg += text[1]
	file.close()
	return str_ext, str_reg

def WriteFile(filename, str_ext, str_reg):
	file = open(filename, "w", encoding="utf-8")
	file.write(str_ext)
	file.write(str_reg)
	file.close()

def RegistMainFunctions(src_path, tar_path):
	str_ext = "extern int ConsoleRegister(const char* cmd, void* entry);\n\n"
	str_reg = "\nvoid py_console_resister_main(void)\n{\n"
	for dirpath,dirname,filename in os.walk(src_path):
		for name in filename:
			if name.endswith(".c") or name.endswith(".cpp"):
				filepath = os.path.join(dirpath,name)
				text = ReadFile(filepath)
				str_ext += text[0]
				str_reg += text[1]
	str_reg += "\n}\n"
	WriteFile(tar_path, str_ext, str_reg)

def main(foldername):
	#如果目录不存在则创建目录
	ret = os.path.exists("./build/" + foldername + "/py_cpp/")
	if not ret:
		os.mkdir("./build/" + foldername + "/py_cpp/")

	RegistMainFunctions("./src", "./build/" + foldername + "/py_cpp/py_console_register.cpp")
